import React, { memo,useState,useEffect,useRef,useCallback } from 'react'

import {shallowEqual, useDispatch, useSelector} from 'react-redux'

import {
  getSongDetailAction,
  changeSequenceAction,
  changeCurrentIndexAndSongAction,
  changeCurrentLyricIndex
} from '../store/actionCreators'

import {getSizeImage, formatDate, getPlaySong} from '@/utils/format-utils'

import {Slider, message} from 'antd'
import {
  PlaybarWrapper,
  Control,
  PlayInfo,
  Operator
} from './style';

export default memo(function ZHAppPlayerBar() {
  // 记录当前播放时间
  const [currentTime, setCurrentTime] = useState(0);
  const [progress, setProgress] = useState(0);
  const [isChanging, setIsChanging] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);

  // redux hook
  const {currentSong, sequence,lyricList,currentLyricIndex} =useSelector(state => ({
    currentSong:state.getIn(["player", "currentSong"]),
    sequence:state.getIn(["player","sequence"]),
    lyricList:state.getIn(["player","lyricList"]),
    currentLyricIndex:state.getIn(["player","currentLyricIndex"])
  }), shallowEqual)

  const dispatch = useDispatch()
  // other hook
  useEffect(() => {
    dispatch(getSongDetailAction(167876))
  },[dispatch])

  const audioRef = useRef()
  
// 暂停时，滑块再移动播放歌曲
  useEffect(() =>  {
    audioRef.current.src = getPlaySong(currentSong.id);
    audioRef.current.play().then(res => {
      setIsPlaying(true);
    }).catch(err => {
      setIsPlaying(false);
    });
  }, [currentSong]);

  // 图片和歌手名字的处理,防止刚开始拿不到数据
  const picUrl = (currentSong.al && currentSong.al.picUrl) || ""
  const singerName =(currentSong.ar && currentSong.ar[0].name) || "未知歌手"
  // 歌曲总时长
  const duration = currentSong.dt || 0
  const showDuration = formatDate(duration, "mm:ss")
  const showCurrentTime = formatDate(currentTime, "mm:ss")
  // 判断是否播放，修改播放暂停的状态
  const playMusic = useCallback(() => {
    setIsPlaying(!isPlaying);
    isPlaying ? audioRef.current.pause() : audioRef.current.play()
  }, [isPlaying]);
  // 监听播放进度
  const timeUpdate = (e) => {
    const currentTime = e.target.currentTime;
    if (!isChanging) {
      setCurrentTime(currentTime * 1000);
      setProgress((currentTime * 1000) / duration * 100);
    }
    // 拿到每一句歌词
    let i =0
    for(; i<lyricList.length; i++){
      let lyricItem = lyricList[i]
      if(currentTime *1000 <lyricItem.time){
        break
      }
    }
    // 对rudex操作频繁，需要优化
    if(currentLyricIndex !== i-1 ){
      dispatch(changeCurrentLyricIndex(i-1))
      const content = lyricList[i-1] && lyricList[i-1].content
      console.log(content)
      message.open({
        key:"lyric",    //key相同只出现一个
        content:content, //刚开始为 0 拿不到第一句歌词
        duration:0 //一直播放
      })
    }

  }


  //监听滑块的改变产生的回调
  const sliderChange = useCallback((value) => {
    setIsChanging(true);
    const currentTime = value / 100 * duration;
    // console.log("滑块改变:", currentTime)
    setCurrentTime(currentTime);
    setProgress(value);
  },[duration])
  //滑块暂停时产生的回调
  const sliderAfterChange =useCallback((value) => {
    // console.log(value, duration)
    const currentTime = value / 100 * duration / 1000;
    // console.log(currentTime)
    audioRef.current.currentTime = currentTime;
    setCurrentTime(currentTime * 1000);
    setIsChanging(false);

    if (!isPlaying) {
      playMusic();
    }
  }, [duration, isPlaying, playMusic])

  const changeSequence = () => {
    let currentSequence = sequence +1
    console.log(currentSequence)
    if(currentSequence > 2){
      currentSequence = 0
    }
    dispatch(changeSequenceAction(currentSequence));
  }

  const changeMusic = (tag) => {
    dispatch(changeCurrentIndexAndSongAction(tag))
    console.log(tag)
  }
  // 一首歌播完的回调
  const handleMusicEnded =() => {
    if(sequence === 2){ //单曲循环
      audioRef.current.currentTime = 0  //
      audioRef.current.play()
    } else {
      dispatch(changeCurrentIndexAndSongAction(1))
    }
  }
  return (
    <PlaybarWrapper className="sprite_playbar">
      <div className="content wrap-v2">
        <Control isPlaying={isPlaying}>
          <button className="sprite_playbar btn prev" onClick={e => changeMusic(-1)}></button>
          <button className="sprite_playbar btn play" onClick={e => playMusic()}></button>
          <button className="sprite_playbar btn next" onClick={e => changeMusic(1)}></button>
        </Control>
        <PlayInfo>
          <div className="image">
            <a href="/#">
              <img src={getSizeImage(picUrl, 35)} alt="" />
            </a>
          </div>
          <div className="info">
            <div className="song">
              <span className="song-name">{currentSong.name}</span>
              <span href="#/" className="singer-name">{singerName}</span>
            </div>
            {/* 进度条区域 */}
            <div className="progress">
              <Slider defaultValue={30}
                      value={progress}
                      onChange={sliderChange} 
                      onAfterChange={sliderAfterChange}              
              />
              {/* 歌曲时间 */}
              <div className="time">
                  <span className="now-time">{showCurrentTime}</span>
                  <span className="divider">/</span>
                  <span className="total-time">{showDuration}</span>
              </div>
            </div>
          </div>
        </PlayInfo>
        <Operator sequence={sequence}>
          <div className="left">
            <button className="sprite_playbar btn favor"></button>
            <button className="sprite_playbar btn share"></button>
          </div>
          {/* 右侧操作：声音、循环、播放列表 */}
          <div className="right">
            <button className="sprite_playbar btn volume"
                    ></button>
            <button className="sprite_playbar btn loop" 
                    onClick={e => changeSequence()}></button>
            <button className="sprite_playbar btn playlist"
                    ></button>
          </div>
        </Operator>
      </div>
      <audio ref={audioRef} 
             onTimeUpdate={e => timeUpdate(e)}
             onEnded={e => handleMusicEnded()}
             />
    </PlaybarWrapper>
  )
})
